#!/usr/bin/env python3
# encoding: utf-8

#Conditions definition of columns that can be merged,Here, we assume that the time is between 1978 and 10000 years
#We can modify this conditions control which column not collapsing
def validYear(yearStr):
  if not yearStr.isdigit():
    return False
  year = int(yearStr)
  if 1978<year<10000:
    return True
  else:
    return False

# my defined Table Info  for record table header
class MyTableInfo:
  colNames =[]
  years =[]

#my defined Database, we assume there is only one table in a DB(key value)
class MyKvDB:
  tableInfo = MyTableInfo()
  tableData = []
  outputArray = []
  def __init__(self,colDefineString):
    print("init db now")
    self.outputArray = []
    self.tableData = []
    colItems = colDefineString.strip().split(",")
    for item in colItems:
      item = item.strip()
      if validYear(item):
        self.tableInfo.years.append(item)
      else:
        self.tableInfo.colNames.append(item)
    self.displayTableInfo()

  def displayTableInfo(self):

    print("my table header is ")
    for col in self.tableInfo.colNames:
      print(col)
    print("below line can be collapsing")
    for year in self.tableInfo.years:
      print(year)

  def displayTableData(self):

    self.displayTableInfo()
    for itemData in self.tableData:
      print(itemData)


  def InsetItems(self,itemsStr):

    colItems = itemsStr.strip().split(",")
    itemCount = len(self.tableInfo.colNames)+len(self.tableInfo.years)

    if  not len(colItems) == itemCount:
      print("inValid data , not insert sucessful ")
      return False

    yearcaseDict = {}
    dataCount = len(self.tableInfo.colNames)

    for yearData in self.tableInfo.years:
      yearcaseDict[yearData] = colItems[dataCount]
      dataCount += 1

    self.tableData.append({colItems[0]:yearcaseDict})

  def reshapeOutput(self):
    outputArray = []
    print("reshape collapsing columns now")
    print("print table header first")
    headStr = "country,year,cases"
    print(headStr)
    self.outputArray.append(headStr)
    for year in self.tableInfo.years:
      for dict in self.tableData:
        for key,valule in dict.items():
          if year in valule:
            self.outputArray.append(key.strip()+","+year+","+valule[year])

  def outputToFile(self,fileName,stdoutput = True):

    with open(fileName,"w") as f:
      for line in self.outputArray:
        f.write(line+"\n")
        if True == stdoutput:
          print(line)


if __name__ == '__main__':
  print("pls input table header first for init db  eg.  country,1999,2000")
  tableHeader = input()
  db = MyKvDB(tableHeader)
  while True:
    dataInsertLine = input("input valid data for insert db，return for exit")
    if 0 == len(dataInsertLine):
      print("insert  finish")
      break
    db.InsetItems(dataInsertLine)
  print("*"*80)
  db.displayTableData()
  db.reshapeOutput()
  db.outputToFile("re.txt")





